<?php

namespace application\admin\controllers;

use mz\ars\Category;
use Yii;
use mz\controllers\AdminController as Controller;

class CategoryController extends Controller
{
    # 分类列表页面
    public function actionIndex()
    {
        $list = Category::getAllCategory();
        return $this->render('index',compact('list'));
    }

    # 加载添加分类 | 添加子类 或者 父级分类 页面
    public function actionAdd()
    {
        $id = intval(Yii::$app->request->get("id",0));
        $pInfo = !empty($id) ? Category::findModel($id) : [];
        return $this->render('add',compact('pInfo'));
    }

    # 编辑子级分类页面
    public function actionEdit()
    {
        $id = intval(Yii::$app->request->get('id'));
        if (empty($id)) throw new \Exception("参数错误，非法请求");

        $cate = Category::findModel($id); # 获取当前分类的信息
        $pInfo = Category::findModel([$cate['pid']]); # 获取当前分类的父级分类的信息

        return $this->render('add',compact('cate','pInfo'));
    }

    # 编辑 | 添加保存动作
    public function actionSave()
    {
        if (!Yii::$app->request->isAjax) return $this->ajaxReturn(['e' => '2','m' => '请使用正确的请求方式']);
        $params = Yii::$app->request->post();

        $saveData = array_filter($params,function($key){
            return in_array($key , ['id','pid','desc','name','pid']);
        },ARRAY_FILTER_USE_KEY);

        $model = empty($params['id']) ? new Category() : Category::find()->where(['id' => $saveData['id']])->one();
        $model->attributes = $params;

        # 数据验证
        if (!$model->validate()){
            return $this->ajaxReturn(['e' => 1,'m' => "很遗憾，数据验证失败！"]);
        }

        # 执行保存
        $msg = $model->save() ? ['e' => 0,'m' => "恭喜您，分类添加成功！"] : ['e' => '1','很遗憾，分类添加失败'];

        return $this->ajaxReturn($msg);

    }

    # 删除分类
    public function actionDelete()
    {
        if (!Yii::$app->request->isAjax) return $this->ajaxReturn(['e' => '2','m' => '请使用正确的请求方式']);
        $id = intval(Yii::$app->request->post('id',0));
        if (empty($id))return $this->ajaxReturn(['e' => '1','m' => "参数错误"]);
        $model = Category::findOne(['id' => $id]);
        if (empty($model))return $this->ajaxReturn(['e' => '1','m' => '您删除的分类不存在']);

        # todo 此处判断分类下是否有文章存在 存在的情况下不允许删除
        if (!true){
        }

        $msg = $model->delete() ? ['e' => '0','m' => '恭喜您，分类删除成功'] : ['e' => '1','m' => '很遗憾，添加失败'];

        return $this->ajaxReturn($msg);
    }
}